#!/usr/bin/python
#coding:utf8
'''
Interpreter
'''

class Expression:
    """抽象表达式类"""
    def interpret(self, context):
        pass

class Constant(Expression):
    """终结符表达式类，表示常量"""
    def __init__(self, value):
        self.value = value

    def interpret(self, context):
        return self.value

class Variable(Expression):
    """终结符表达式类，表示变量"""
    def __init__(self, name):
        self.name = name

    def interpret(self, context):
        return context[self.name]

class Add(Expression):
    """非终结符表达式类，表示加法"""
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def interpret(self, context):
        return self.left.interpret(context) + self.right.interpret(context)

class Multiply(Expression):
    """非终结符表达式类，表示乘法"""
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def interpret(self, context):
        return self.left.interpret(context) * self.right.interpret(context)

# 测试解释器
if __name__ == "__main__":
    # 创建一个上下文（变量表）
    context = {'a': 5, 'b': 3}

    # 构造表达式：a + b * a + 10
    expr = Add(Add(Variable('a'), Multiply(Variable('b'), Variable('a'))),Constant(10))

    # 解释并执行表达式
    result = expr.interpret(context)
    print(f"Result of 'a + b * a + 10' is: {result}")  # 输出结果应为 30